package com.hcy.app.screen.music.components

import android.Manifest.permission.READ_MEDIA_AUDIO
import android.annotation.SuppressLint
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.ShoppingCart
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.res.vectorResource
import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.media3.common.MediaItem
import androidx.navigation.compose.rememberNavController
import com.hcy.app.LocalNavController
import com.hcy.app.R
import com.hcy.app.screen.music.view.PlayerViewModel

@Preview
@Composable
fun PreviewPlayerScreen() {
    val navController = rememberNavController()
    CompositionLocalProvider(LocalNavController provides navController) {
//        MUSIC_PLAY()
    }
}

// 格式化时间显示 (秒 -> 分:秒)
@SuppressLint("DefaultLocale")
private fun formatTime(seconds: Int): String {
    val minutes = seconds / 60
    val remainingSeconds = seconds % 60
    return String.format("%d:%02d", minutes, remainingSeconds)
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MUSIC_PLAY(
    playerVM: PlayerViewModel = hiltViewModel(),
){
    // 抽屉
    val sheetState = rememberModalBottomSheetState()
    var showBottomSheet by remember { mutableStateOf(false) }
    // 播放器
    val playerState by playerVM.playerState.collectAsState()

    val navController = LocalNavController.current
    val ctx = LocalContext.current

    // 创建权限启动器
    val permissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission(),
        onResult = {
        }
    )

    // 处理初始播放逻辑
    LaunchedEffect(Unit){
        // 某次系统更新后 READ_MEDIA_AUDIO 就需要动态授权了。
        // mainfest 直接写权限后还需要动态权限，每次系统更新貌似都需要重新授权，莫名其妙！
        if (ContextCompat.checkSelfPermission(ctx, READ_MEDIA_AUDIO.toString()) != PERMISSION_GRANTED) {
            permissionLauncher.launch(READ_MEDIA_AUDIO.toString()) // 自动弹出权限请求对话框
        }
        if (playerState.songList.isNotEmpty()){
            // 加载初始音乐,优先接着上一次的播放，没有上一次的音乐就从第一首歌开始
            val currentIndex = playerState.songList.indexOfFirst { it.id == playerState.currentSongId }
            val song = if (currentIndex==-1){
                playerState.songList[0]
            }else{
                playerState.songList[currentIndex]
            }
            playerVM.setMediaItem(MediaItem.Builder().setUri(song.filePath).build(),song.id)
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Blue)
            .clickable {
                showBottomSheet = false
            },
    ){
        // 内容区域
        Column(
            modifier = Modifier
                .fillMaxSize()
                .systemBarsPadding()
            ,
        ){
            // 顶部功能菜单
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                ,
                horizontalArrangement = Arrangement.End,
            ) {
                IconButton(
                    content ={
                        Icon(
                            imageVector = Icons.Default.Home,
                            contentDescription = "首页",
                            tint = Color.White
                        )
                    },
                    onClick = {
                        navController.navigate("home")
                    }
                )
                IconButton(
                    content ={
                        Icon(
                            imageVector = Icons.Default.ShoppingCart,
                            contentDescription = "在线下载",
                            tint = Color.White
                        )
                    },
                    onClick = {
                        Toast.makeText(ctx,"还没做这个功能！", Toast.LENGTH_SHORT).show()
                    }
                )
                IconButton(
                    content ={
                        Icon(
                            imageVector = Icons.Default.Add,
                            contentDescription = "wifi 传歌",
                            tint = Color.White
                        )
                    },
                    onClick = {
                        navController.navigate("musicUpload")
                    }
                )
            }

            // 歌词区域
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
                    .padding(1.dp),
                verticalArrangement = Arrangement.Top
            ) {
                // 背景图片
                Image(
                    painter = painterResource(id = R.drawable.hcy_mv2), // 替换为你的图片资源
                    contentDescription = "背景图",
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop, // 控制图片填充方式
                    alpha = 0.9f // 设置透明度
                )
                // 标题
                Text(
                    text = "找一个字代替", modifier = Modifier
                        .fillMaxWidth()
                        .padding(1.dp),
                    color = Color.DarkGray, fontSize = 26.sp,
                    fontStyle = FontStyle.Italic, fontFamily = FontFamily.Cursive,
                    textAlign = TextAlign.Center
                )
                Spacer(Modifier.height(16.dp)) // 间隔
                // 歌词
                Text(
                    text = "显示歌词，我还没写", modifier = Modifier
                        .fillMaxWidth()
                        .padding(1.dp),
                    color = Color.DarkGray, fontSize = 26.sp,
                    textAlign = TextAlign.Center
                )
            }

            // 控制区域
            Column (
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 10.dp)
                    .padding(bottom = 20.dp)
            ) {
                // 进度条
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                ) {
                    Slider(
                        value = playerState.currentPosition.toFloat(),
                        valueRange = 0f..playerState.duration.toFloat(),
                        onValueChange = {newValue->
                            playerVM.seekTo(newValue.toLong())
                        },
                        colors = SliderDefaults.colors(
                            thumbColor = Color(0xFF4A90E2),
                            activeTrackColor = Color(0xFF4A90E2),
                            inactiveTrackColor = Color(0xFF2D3748)
                        )
                    )

                }
                // 文字描述信息
                Row(
                    modifier = Modifier.fillMaxWidth()
                        .padding(horizontal =10.dp),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = formatTime(playerState.currentPosition.toInt()/1000),
                        color = Color.White,
                        fontSize = 14.sp
                    )
                    Text(
                        text = formatTime(playerState.duration.toInt()/1000),
                        color = Color.White,
                        fontSize = 14.sp
                    )
                }
                // 控制按钮
                Row(
                    modifier = Modifier
                        .fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    val rangIcon=arrayOf(R.drawable.ic_one, R.drawable.ic_rang,R.drawable.ic_random)
                    // 循环方式
                    IconButton(onClick = {
                        playerVM.toggleLoopMode()
                    }) {
                        Icon(
                            painter = rememberVectorPainter(image = ImageVector.vectorResource(rangIcon[playerState.loopModel])),
                            contentDescription = "Favorite",
                            tint = Color.White
                        )
                    }

                    // 上一曲按钮
                    IconButton(onClick = { playerVM.clickLastMedia() }) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "Previous",
                            tint = Color.White,
                            modifier = Modifier.size(36.dp)
                        )
                    }

                    // 播放/暂停按钮
                    IconButton(
                        onClick = {
                            // 点击播放按钮
                            playerVM.togglePlayPause()
                        },
                        modifier = Modifier
                            .size(64.dp)
                            .background(Color(0xFF4A90E2), CircleShape)
                    ) {
                        Icon(
                            painter = rememberVectorPainter(image = ImageVector.vectorResource(if (playerState.isPlaying)  R.drawable.ic_stop else R.drawable.ic_play )),
                            contentDescription = if (playerState.isPlaying) "Pause" else "Play",
                            tint = Color.White,
                            modifier = Modifier.size(36.dp)
                        )
                    }

                    // 下一曲按钮
                    IconButton(onClick = { playerVM.clickNextMedia() }) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowForward,
                            contentDescription = "Next",
                            tint = Color.White,
                            modifier = Modifier.size(36.dp)
                        )
                    }

                    // 更多选项按钮
                    IconButton(onClick = {
                        showBottomSheet = true
                    }) {
                        Icon(
                            imageVector = Icons.Default.Menu,
                            contentDescription = "More",
                            tint = Color.White
                        )
                    }
                }
            }

            // 底部抽屉
            if (showBottomSheet) {
                ModalBottomSheet(
                    onDismissRequest = { showBottomSheet = false },
                    sheetState = sheetState
                ) {
                    // 抽屉内容
                    Song_List_Screen()
                }
            }
        }
    }
}
